package com.pearl.db.demo.mp.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.pearl.db.demo.mp.entity.User;
import com.pearl.db.demo.mp.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author pearl
 * @since 2023-04-12
 */
@Slf4j
@RestController
@RequestMapping("/user")
@CacheConfig(cacheNames = {"userController"})
public class UserController {

    @Autowired
    IUserService userService;

    @GetMapping("/list")
    //@Cacheable(keyGenerator = "myKeyGenerator")
    @Cacheable(key = "#root.methodName")
    public Object list(String userName, String loginName) {
        log.info("数据库条件查询列表");
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .eq(StrUtil.isNotEmpty(userName), User::getUserName, userName)
                .eq(StrUtil.isNotEmpty(loginName), User::getLoginName, loginName);
        return userService.list(wrapper);
    }

    @GetMapping("/save")
    @CacheEvict
    public Object save() {
        User user = new User();
        user.setUserName(LocalDateTime.now().toString());
        user.setPassword("123456");
        user.setLoginName("kun");
        userService.save(user);
        return "操作成功";
    }

    @GetMapping("/update")
    @CachePut
    public User update(String id) {
        log.info("进入更新操作");
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<User>().eq(User::getUserId, id).set(User::getUserName, "kunkunkun");
        userService.update(updateWrapper);
        return userService.getById(id);
    }


    //
    @Caching(
            evict = {
                    @CacheEvict("primary"),
                    @CacheEvict(cacheNames = "secondary", key = "#p0")
            })
    public User importUser(String id) {
        return new User();
    }
}
